<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="仓库类型" prop="productType">
              <el-select v-model="queryParams.warehouseType" placeholder="请选择仓库类型" clearable>
                <el-option v-for="dict in warehouse_type" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="仓库名称" prop="wid">
              <el-input v-model="queryParams.warehouseName" placeholder="请输入仓库名称" clearable />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <!--          <el-col :span="1.5">-->
          <!--            <el-button v-hasPermi="['lingxing:warehouseStockRealTime:add']" type="primary" plain icon="Plus" @click="handleAdd">新增 </el-button>-->
          <!--          </el-col>-->
          <!--          <el-col :span="1.5">-->
          <!--            <el-button-->
          <!--              v-hasPermi="['lingxing:warehouseStockRealTime:edit']"-->
          <!--              type="success"-->
          <!--              plain-->
          <!--              icon="Edit"-->
          <!--              :disabled="single"-->
          <!--              @click="handleUpdate()"-->
          <!--              >修改-->
          <!--            </el-button>-->
          <!--          </el-col>-->
          <!--          <el-col :span="1.5">-->
          <!--            <el-button-->
          <!--              v-hasPermi="['lingxing:warehouseStockRealTime:remove']"-->
          <!--              type="danger"-->
          <!--              plain-->
          <!--              icon="Delete"-->
          <!--              :disabled="multiple"-->
          <!--              @click="handleDelete()"-->
          <!--              >删除-->
          <!--            </el-button>-->
          <!--          </el-col>-->
          <!--          <el-col :span="1.5">-->
          <!--            <el-button v-hasPermi="['lingxing:warehouseStockRealTime:export']" type="warning" plain icon="Download" @click="handleExport"-->
          <!--              >导出-->
          <!--            </el-button>-->
          <!--          </el-col>-->
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleSyncData">同步数据</el-button>
          </el-col>
          <el-col :span="15">
            数据更新时间：
            <el-text>{{ newestUpdateTime }}</el-text>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @query-table="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="warehouseStockRealTimeList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column v-if="false" label="id" align="center" prop="id" />
        <!--        <el-table-column label="仓库id" align="center" prop="wid" />-->
        <el-table-column label="仓库名称" align="center" prop="warehouseName" />
        <el-table-column label="属性" align="center" prop="warehouseType">
          <template #default="scope">
            {{ warehouse_type.find((item) => Number(item.value) === scope.row.warehouseType)?.label }}
          </template>
        </el-table-column>
        <el-table-column label="产品种类" align="center" prop="productIdQuantity" />
        <el-table-column label="可用量" align="center" prop="productValidNum" />
        <el-table-column label="待检待上架量" align="center" prop="productQcNum" />
        <el-table-column label="锁定量" align="center" prop="productLockNum" />
        <el-table-column label="在途量" align="center" prop="productOnway" />
        <el-table-column label="次品量" align="center" prop="productBadNum" />
        <el-table-column label="待到货量" align="center" prop="quantityReceive" />
        <el-table-column align="center" prop="productExpectedTotal">
          <template #header>
            <span>
              预计总量
              <el-tooltip effect="dark" content="【可用量+ 待检上架量 + 锁定量 + 次品量 + 在途量 + 待到货量】" placement="top-start">
                <svg-icon icon-class="question" />
              </el-tooltip>
            </span>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="productTotal">
          <template #header>
            <span>
              总量
              <el-tooltip effect="dark" content="【可用量+ 待检上架量 + 锁定量 + 次品量】" placement="top-start">
                <svg-icon icon-class="question" />
              </el-tooltip>
            </span>
          </template>
        </el-table-column>
        <el-table-column label="货值" align="center" prop="productCostTotal">
          <template #default="scope">{{ Number(scope.row.productCostTotal).toFixed(2) }}</template>
        </el-table-column>
        <el-table-column label="费用" align="center" prop="transitHeadCost">
          <template #default="scope">{{ Number(scope.row.transitHeadCost).toFixed(2) }}</template> </el-table-column
        >3
        <el-table-column label="库存成本" align="center" prop="stockCostTotal">
          <template #default="scope">{{ Number(scope.row.stockCostTotal).toFixed(2) }}</template>
        </el-table-column>
        <!--        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">-->
        <!--          <template #default="scope">-->
        <!--            <el-tooltip content="修改" placement="top">-->
        <!--              <el-button-->
        <!--                v-hasPermi="['lingxing:warehouseStockRealTime:edit']"-->
        <!--                link-->
        <!--                type="primary"-->
        <!--                icon="Edit"-->
        <!--                @click="handleUpdate(scope.row)"-->
        <!--              ></el-button>-->
        <!--            </el-tooltip>-->
        <!--            <el-tooltip content="删除" placement="top">-->
        <!--              <el-button-->
        <!--                v-hasPermi="['lingxing:warehouseStockRealTime:remove']"-->
        <!--                link-->
        <!--                type="primary"-->
        <!--                icon="Delete"-->
        <!--                @click="handleDelete(scope.row)"-->
        <!--              ></el-button>-->
        <!--            </el-tooltip>-->
        <!--          </template>-->
        <!--        </el-table-column>-->
      </el-table>

      <pagination v-show="total > 0" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" :total="total" @pagination="getList" />
    </el-card>
    <!-- 添加或修改领星仓库即时库存对话框 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="500px" append-to-body>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="WarehouseStockRealTime" lang="ts">
import {
  listWarehouseStockRealTime,
  getWarehouseStockRealTime,
  delWarehouseStockRealTime,
  addWarehouseStockRealTime,
  updateWarehouseStockRealTime,
  syncData,
  getNewestUpdateTime
} from '@/api/lingxing/warehouseStockRealTime';
import { WarehouseStockRealTimeVO, WarehouseStockRealTimeQuery, WarehouseStockRealTimeForm } from '@/api/lingxing/warehouseStockRealTime/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { warehouse_type } = toRefs<any>(proxy?.useDict('warehouse_type'));

const warehouseStockRealTimeList = ref<WarehouseStockRealTimeVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const warehouseStockRealTimeFormRef = ref<ElFormInstance>();
const newestUpdateTime = ref('');

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: WarehouseStockRealTimeForm = {
  id: undefined,
  wid: undefined,
  warehouseType: undefined,
  productIdQuantity: undefined,
  productValidNum: undefined,
  productQcNum: undefined,
  productLockNum: undefined,
  productOnway: undefined,
  productBadNum: undefined,
  quantityReceive: undefined,
  productExpectedTotal: undefined,
  productTotal: undefined,
  productCostTotal: undefined,
  transitHeadCost: undefined,
  stockCostTotal: undefined
};
const data = reactive<PageData<WarehouseStockRealTimeForm, WarehouseStockRealTimeQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    wid: undefined,
    warehouseType: undefined,
    warehouseName: undefined,
    productIdQuantity: undefined,
    productValidNum: undefined,
    productQcNum: undefined,
    productLockNum: undefined,
    productOnway: undefined,
    productBadNum: undefined,
    quantityReceive: undefined,
    productExpectedTotal: undefined,
    productTotal: undefined,
    productCostTotal: undefined,
    transitHeadCost: undefined,
    stockCostTotal: undefined,
    params: {}
  },
  rules: {
    id: [{ required: true, message: 'id不能为空', trigger: 'blur' }],
    wid: [{ required: true, message: '仓库id不能为空', trigger: 'blur' }],
    warehouseType: [{ required: true, message: '仓库类型：1 本地仓，3 海外仓不能为空', trigger: 'change' }],
    productIdQuantity: [{ required: true, message: '产品种类不能为空', trigger: 'blur' }],
    productValidNum: [{ required: true, message: '可用量不能为空', trigger: 'blur' }],
    productQcNum: [{ required: true, message: '待检待上架量不能为空', trigger: 'blur' }],
    productLockNum: [{ required: true, message: '锁定量不能为空', trigger: 'blur' }],
    productOnway: [{ required: true, message: '在途量不能为空', trigger: 'blur' }],
    productBadNum: [{ required: true, message: '次品量不能为空', trigger: 'blur' }],
    quantityReceive: [{ required: true, message: '待到货量不能为空', trigger: 'blur' }],
    productExpectedTotal: [
      {
        required: true,
        message: '预计总量【可用量+ 待检上架量 + 锁定量 + 次品量 + 在途量 + 待到货量】不能为空',
        trigger: 'blur'
      }
    ],
    productTotal: [{ required: true, message: '总量【可用量+ 待检上架量 + 锁定量 + 次品量】不能为空', trigger: 'blur' }],
    productCostTotal: [{ required: true, message: '货值不能为空', trigger: 'blur' }],
    transitHeadCost: [{ required: true, message: '费用不能为空', trigger: 'blur' }],
    stockCostTotal: [{ required: true, message: '库存成本不能为空', trigger: 'blur' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询领星仓库即时库存列表 */
const getList = async () => {
  loading.value = true;
  const res = await listWarehouseStockRealTime(queryParams.value);
  warehouseStockRealTimeList.value = res.rows;
  total.value = res.total;
  loading.value = false;

  const res1 = await getNewestUpdateTime();
  newestUpdateTime.value = res1.msg;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  warehouseStockRealTimeFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: WarehouseStockRealTimeVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加领星仓库即时库存';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: WarehouseStockRealTimeVO) => {
  reset();
  const _id = row?.id || ids.value[0];
  const res = await getWarehouseStockRealTime(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改领星仓库即时库存';
};

/** 提交按钮 */
const submitForm = () => {
  warehouseStockRealTimeFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateWarehouseStockRealTime(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addWarehouseStockRealTime(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: WarehouseStockRealTimeVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除领星仓库即时库存编号为"' + _ids + '"的数据项？').finally(() => (loading.value = false));
  await delWarehouseStockRealTime(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'lingxing/warehouseStockRealTime/export',
    {
      ...queryParams.value
    },
    `仓库实时库存_${new Date().getTime()}.xlsx`
  );
};

/** 同步数据按钮操作 */
const handleSyncData = async (row?: WarehouseStockRealTimeVO) => {
  loading.value = true;
  await proxy?.$modal.confirm('是否同步领星仓库即时库存数据项？').finally(() => (loading.value = false));
  loading.value = true;
  await syncData().finally(() => (loading.value = false));
  proxy?.$modal.msgSuccess('同步数据成功!');
  loading.value = true;
  await getList().finally(() => (loading.value = false));
};

onMounted(() => {
  getList();
});
</script>
